﻿using AutoMapper;
using System.Text.Json;
using System.Web;
using TrackSystem.Contracts;
using TrackSystem.Entities.Dtos.Logic;
using TrackSystem.Entities.Extensions;
using TrackSystem.IO.Utils;

namespace TrackSystem.UI.Server.HttpRepository.Logic
{
    /// <summary>
    /// 逻辑表达式处理仓储类
    /// </summary>
    public class LogicHttpRepository : HttpRepository<LogicDto, LogicForCreateDto>, ILogicHttpRepository
    {
        private readonly HttpClient client;
        private readonly IMapper mapper;

        /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name="client"></param>
        /// <param name="mapper"></param>
        public LogicHttpRepository(HttpClient client, IMapper mapper) : base(client, mapper)
        {
            this.client = client;
            this.mapper = mapper;
            Name = "logic";
        }

        /// <summary>
        /// 测试表达式
        /// </summary>
        /// <param name="expression"></param>
        /// <returns></returns>
        public async Task<FormulaResult> TestForula(string expression)
        {
            string encodeUrl = HttpUtility.UrlEncode(expression);
            var response = await client.GetAsync($"api/logic/test?formula={encodeUrl}");
            var content = await response.Content.ReadAsStringAsync();
            var result = JsonSerializer.Deserialize<FormulaResult>(
                content, new JsonSerializerOptions { PropertyNameCaseInsensitive = true });
            return result ??= FormulaResult.Ok("Empty result");
        }

    }
}
